<template>
  <div  class="clsmenu">
    <el-menu
        :default-active="activeIndex"
        class="el-menu-demo"
        mode="horizontal"
        @select="handleSelect"
    >
      <el-sub-menu index="file">
        <template #title>画面</template>
        <el-menu-item index="openDrw">打开本地文件</el-menu-item>
        <el-menu-item index="saveDrw">保存在本地文件</el-menu-item>

        <el-menu-item index="loadDrwFile">打开后台文件</el-menu-item>
        <el-menu-item index="saveDrwFile">保存在后台文件</el-menu-item>
        
        <el-menu-item index="saveToLocalStorage">保存在内存</el-menu-item>
        <el-menu-item index="setScale">比例</el-menu-item>
        <el-menu-item index="previewDrw">预览</el-menu-item>
        <el-menu-item index="clearDrw">清除</el-menu-item>
      </el-sub-menu>

      <el-sub-menu index="obj">
        <template #title>对象</template>
        <el-menu-item index="lock"  :disabled="!curComponent || curComponent.isLock" >锁定</el-menu-item>
        <el-menu-item index="unlock" :disabled="!curComponent || !curComponent.isLock" >解锁</el-menu-item>

        <el-menu-item index="compose" :disabled="!areaData.components.length" >组合</el-menu-item>
        <el-menu-item index="decompose" :disabled="!curComponent || curComponent.isLock || curComponent.component != 'Group'" >拆分</el-menu-item>

      </el-sub-menu>

      <el-sub-menu index="objmove">
        <template #title>移动</template>
        <el-menu-item index="moveup" :disabled="!curComponent" >上移</el-menu-item>
        <el-menu-item index="movedown" :disabled="!curComponent" >下移</el-menu-item>
        <el-menu-item index="movetop" :disabled="!curComponent" >置顶</el-menu-item>
        <el-menu-item index="movebottom" :disabled="!curComponent" >置底</el-menu-item>
      </el-sub-menu>

      <el-sub-menu index="hg3000">
        <template #title>hg3000</template>
        <el-menu-item index="connectSrv">联接服务器</el-menu-item>

        <el-sub-menu index="setCurrentMode">
          <template #title>{{ strModeRun }}</template>
          <el-menu-item index="setModeRun">设为运行</el-menu-item>
          <el-menu-item index="setModeDesign">设为设计</el-menu-item>
      </el-sub-menu>
      
        <el-menu-item index="freshdrw">实时数据刷新</el-menu-item>
        <el-menu-item index="alarmwin">报警窗口</el-menu-item>
        <!-- <el-menu-item index="freshProjectSave">刷新报警项目</el-menu-item> -->
        <el-menu-item index="systemmanage">系统管理</el-menu-item>
        <el-menu-item index="about">关于...</el-menu-item>
      </el-sub-menu>      

    </el-menu>

    <Preview v-if="isShowPreview" :is-screenshot="isScreenshot" @close="handlePreviewChange" />
    <input type="file" ref="fileInput" style="display: none;" @change="handleFileInputChange" />

    <DlgAlarmDisplay :dialog-visible="isShowAlarm"  @res-alarm-display="handleResultAlarm"></DlgAlarmDisplay>

    <DlgBackDrwFile  ref="refDlgDrwFileOpen"  :dialog-visible="isShowBackDrwFileOpen" :config-new-file="isConfigNewFile" @res-file="handleResultLoadBackDrwFile" > </DlgBackDrwFile>
    <DlgBackDrwFile  ref="refDlgDrwFile"  :dialog-visible="isShowBackDrwFileSave" :config-new-file="isConfigNewFile1" @res-file="handleResultSaveDrwFile" > </DlgBackDrwFile>
    <DlgAbout  :dialog-visible="isShowAbout"  @res-about="handleResultAbout"></DlgAbout>


  </div>
</template>

<script>
// @ is an alias to /src

import componentList from "@/custom-component/component-list";

import generateID from '@/utils/generateID'
import toast from '@/utils/toast'
import { mapState } from 'vuex'
import Preview from '@/components/Editor/Preview'
import AceEditor from '@/components/Editor/AceEditor.vue'
import { commonStyle, commonAttr } from '@/custom-component/component-list'
import eventBus from '@/utils/eventBus'
import { $ } from '@/utils/utils'
import changeComponentsSizeWithScale, { changeComponentSizeWithScale } from '@/utils/changeComponentsSizeWithScale'

import { deepCopy } from '@/utils/utils'

import { ElMessage, ElMessageBox } from 'element-plus'

import request from "@/utils/drawutils/request"

import DlgAlarmDisplay from "@/draw/statusbar/DlgAlarmDisplay.vue"
import DlgBackDrwFile from "./drwfile/DlgBackDrwFile.vue";
import DlgAbout from "./drwfile/DlgAbout.vue";

export default {
  name: 'DrawMenu',
  components: {
    Preview, DlgAlarmDisplay,  DlgBackDrwFile, DlgAbout
  },
  data() {
    return {
      activeIndex: "",

      isShowPreview: false,
      isShowAceEditor: false,
      timer: null,
      isScreenshot: false,
      scale: 100,
      isShowAlarm: false ,
      localStorageName: "drawedt",
      drawFileName: "文件名",

      isShowSaveDrwFile : false ,  // 保存后台文件

      isShowBackDrwFileSave: false,
      isShowBackDrwFileOpen: false,   // 载入后台文件
      isConfigNewFile: false ,
      isConfigNewFile1: true ,
      isShowAbout: false,

    }
  },


  computed: {
    ...mapState([
      'componentData',
      'canvasStyleData',
      'areaData',
      'curComponent',
      'curComponentIndex',
      'isModeRun',
      'projectid',
      'projectExist'
    ]),

    strModeRun(   ){
      if( this.isModeRun )
        return  "当前模式：运行"
      else
        return  "当前模式：设计"
    },
  },

  created(  ) {
  },

  mounted() {
    let vara = { drawstr: "",  projectid: "3f61812fb43942b4adb71f51e002a471"}
    localStorage.setItem(  "edtaaa", JSON.stringify( vara ) )        

    if( this.$route.query.name ){
      this.localStorageName = this.$route.query.name
    }

    if( this.$route.query.projectid )
      this.$store.commit('setProjectId',  this.$route.query.projectid )  

    this.$store.commit('loadDrwFromLocalStorage', this.localStorageName )

    //删除edt开头的条目
    var array = []
    for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i);          // 获取键名
        const value = localStorage.getItem(key);  // 获取键对应的值
        //console.log(`${key}: ${value}`);
        if( key.startsWith("edt") )
          array.push( key )      
    }
    
    array.forEach(element => {
      localStorage.removeItem( element )
    });
  },

  methods: {
    handleSelect( key, keyPath ){
      // console.log( key, keyPath )
      switch (key){
        case "openDrw":
          this.openDrw(  )
              break
        case "saveDrw":
          this.saveDrw(  )
              break
        case "saveDrwFile":
              this.saveDrwFile(  )
              break
        case "loadDrwFile":
              this.loadDrwFile(  )
              break              
        case "saveToLocalStorage":
          this.saveToLocalStorage(  )
          break                  
        case "previewDrw":
          this.previewDrw( false )
              break
        case "clearDrw":
          this.clearDrw(  )
              break
        case "lock":
          this.lock( )
          break
        case "unlock":
          this.unlock( )
          break
        case "moveup":
          this.upComponent()
          break
        case "movedown":
          this.downComponent()
          break
        case "movetop":
          this.topComponent()
          break
        case "movebottom":
          this.bottomComponent()
          break
        case "compose":
          this.compose( )
          break
        case "decompose":
          this.decompose( )
          break
        case "setScale":
          this.setScale( )
          break
        case "connectSrv":
          this.handleConnectSrv( )
          break          
        case "freshdrw":
          this.handleFresh( )
          break          
        case "alarmwin":
          this.handleAlarm( )
          break    
        case "setModeRun":
          this.$store.commit('setModeRun',  true )
          break    
        case "setModeDesign":
          this.$store.commit('setModeRun',  false )
          break    
        case "about":
          this.isShowAbout = true
          break              
        // case "freshProjectSave":
        //   this.freshProjectSave( )
        //   break     
        case "systemmanage":
          this.$router.push('/sysmanage/freshProjectSave')
          break               
      }

    },

    openDrw(  ){
      this.$refs.fileInput.click();
    },

    handleFileInputChange(event) {
      // Handle the file input change event here
      const file = event.target.files[0];
      // console.log("Selected file:", file);

      const reader = new FileReader();

      reader.onload = () => {
        let fileContent = reader.result;
        this.$store.commit('loaddrw', fileContent )
        this.$store.commit('clearInit', { componentData: this.componentData } )
      };

      reader.readAsText(file);
      this.scale = 100    //新打开的画面显示比例是100
    },

    // loadDrw( content ){
    //   //var webdrw = JSON.parse( content )
    //   this.$store.commit('loaddrw', content )
    //   this.$store.commit('clearInit', { componentData: this.componentData } )
    //   this.$store.commit('setCurComponent', { component: null, index: null })
    //   this.$store.commit('recordSnapshot')
    // },

    saveDrw( ){
      //输入文件名称
      ElMessageBox.prompt('文件名称', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: this.drawFileName,
        inputPlaceholder:  this.drawFileName,
      })
      .then(({ value }) => {
        this.drawFileName =  value
        this.saveToFile( this.drawFileName )
      })
      .catch(() => {
      })      
    },

    //保存成本地文件
    saveToFile( fileName ){
      var save = { canvasData: this.componentData, canvasStyle: this.canvasStyleData }
      var webdrw = JSON.stringify( save )

      //下面的代码将画面数据存入文件中
      var FileSaver = require('file-saver');
      var blob = new Blob([ webdrw ], {type: "text/plain;charset=utf-8"});
      FileSaver.saveAs(blob, fileName  + ".wdrw");
      
      this.$message.success('保存文件成功')
    },

    //保存到后台文件
    async saveDrwFile( ){
      if( !this.projectExist ){
        ElMessage.error("项目代码不存在!需要从管理程序进入。")
        return 
      }
      let obj = {  parent: '/', subdir: '', projectid: this.projectid  }
      // console.log( obj )
      let res = await request.post("/dirfilem/makedir",  obj )
      // console.log( res )
      if( res.code === "1" ){   //只有新创建了用户目录才刷新
         this.$refs.refDlgDrwFile.freshDir( )
      }
      else
        this.$refs.refDlgDrwFile.freshEmptyDir( )
      
      this.isShowBackDrwFileSave = true
    },

    handleResultSaveDrwFile( code , res ){
      if( code === 0 ) {
        this.isShowBackDrwFileSave = false 
        return 
      }

      var save = { canvasData: this.componentData, canvasStyle: this.canvasStyleData }
      var webdrw = JSON.stringify( save )

      //使用post接口发送文件名称及内容到后台保存
      var parm = {savedir: res.savedir, filename: res.filename, drw: webdrw, projectid: this.projectid }
      // console.log( "parm", parm )

      request.post("/drwfile/save", parm ).then(res => {
          // console.log( res )
          if( res.code === "1" ){
            ElMessage({ type: 'success',  message: "保存文件成功!" })
            this.$refs.refDlgDrwFile.freshCurrentDir( );
          }
          else{
            ElMessage({ type: 'error',  message: res.data })
          }

          this.isShowBackDrwFileSave = false 
      })
    },

    async loadDrwFile( ){
      if( !this.projectExist ){
        ElMessage.error("项目代码不存在!需要从管理程序进入。")
        return 
      }
      let obj = {  parent: '/', subdir: '', projectid: this.projectid  }
      console.log( obj )
      let res = await request.post("/dirfilem/makedir",  obj )
      // console.log( res )
      if( res.code === "1" ){   //只有新创建了用户目录才刷新
         this.$refs.refDlgDrwFileOpen.freshDir( )
      }
      else
        this.$refs.refDlgDrwFile.freshEmptyDir( )

      this.isShowBackDrwFileOpen = true 

    },

    handleResultLoadBackDrwFile(  code , res  ){
      if( code === 0 ) {
        this.isShowBackDrwFileOpen = false
        return 
      }

      var parm = {savedir: res.savedir, filename: res.filename, projectid: this.projectid }
      // console.log( "parm:" , parm  )

      request.post("/drwfile/load", parm ).then(res => {
          //console.log( res )
          if( res.code === "1" ){
            this.$store.commit('loaddrw', res.data )
            this.$store.commit('clearInit', { componentData: this.componentData } )

            ElMessage({ type: 'success',  message: "载入文件成功!" })
          }
          else{
            ElMessage({ type: 'error',  message: res.data })
          }

          this.isShowBackDrwFileOpen = false
      })
      
    },

    saveToLocalStorage( ){
      var save = { canvasData: this.componentData, canvasStyle: this.canvasStyleData }
      var webdrw = JSON.stringify( save )

      let savedrwobj = { drawstr: webdrw,  projectid: this.projectid }
      localStorage.setItem( this.localStorageName,  JSON.stringify( savedrwobj )  )
      // console.log("save to ", this.localStorageName )

      this.$message.success('保存内存成功!')
    },

    //绘制画面预览
    previewDrw( isScreenshot ){
      //第一个方案的预览
      // this.isScreenshot = isScreenshot
      // this.isShowPreview = true
      // this.$store.commit('setEditMode', 'preview')
      // console.log("preview")

      //另开tab页面进行预览
      console.log( window.location.origin )

      this.saveToLocalStorage( )

      if (this.$route.query.name)
        window.open( window.location.origin+"/drawapp/runfull?name="+this.$route.query.name, "_blank" )
      else
        window.open( window.location.origin+"/drawapp/runfull?name=drawedt", "_blank" )

        //测试代码
      // this.localStorageName = "view123"
      // this.saveToLocalStorage( )
      // window.open( window.location.origin+"/drawapp/runfull?name=view123", "_blank" )


    },

    clearDrw(  ){
      this.$store.commit('setCurComponent', { component: null, index: null })
      this.$store.commit('setComponentData', [])
      this.$store.commit('recordSnapshot')


      var canvas  = deepCopy( this.canvasStyleData )
      canvas.backgroundColor = '#eee'
      this.$store.commit('aceSetCanvasData', canvas )

    },

    handlePreviewChange() {
      this.isShowPreview = false
      this.$store.commit('setEditMode', 'edit')
    },

    lock() {
      this.$store.commit('lock')
    },

    unlock() {
      this.$store.commit('unlock')
    },

    deleteComponent() {
      setTimeout(() => {
        this.$store.commit('deleteComponent')
        this.$store.commit('recordSnapshot')
      })
    },

    upComponent() {
      setTimeout(() => {
        this.$store.commit('upComponent')
        this.$store.commit('recordSnapshot')
      })
    },

    downComponent() {
      setTimeout(() => {
        this.$store.commit('downComponent')
        this.$store.commit('recordSnapshot')
      })
    },

    topComponent() {
      setTimeout(() => {
        this.$store.commit('topComponent')
        this.$store.commit('recordSnapshot')
      })
    },

    bottomComponent() {
      setTimeout(() => {
        this.$store.commit('bottomComponent')
        this.$store.commit('recordSnapshot')
      })
    },

    compose( ){
      this.$store.commit('compose')
      this.$store.commit('recordSnapshot')
    },

    decompose( ){
      this.$store.commit('decompose')
      this.$store.commit('recordSnapshot')
    },

    setScale( ){
      ElMessageBox.prompt('请输入画面比例(1-500)，原始比例是100%', '画面显示比例', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern:
            // /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
      /^(1|([1-9])|([1-9]\d)|([1-4]\d{2})|(500))$/,
        inputErrorMessage: '无效比例输入',
        inputPlaceholder:  String(this.scale),
      })
          .then(({ value }) => {
            //ElMessage({ type: 'success',  message: `input is:${value}`,   })
            this.scale =  value
            this.handleScaleChange(  )
          })
          .catch(() => {
          })
    },

    //显示比例的改变
    handleScaleChange( ){
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        // 画布比例设一个最小值，不能为 0
        // eslint-disable-next-line no-bitwise
        this.scale = (~~this.scale) || 1
        changeComponentsSizeWithScale(this.scale)
      }, 1000)
    },

    handleConnectSrv(  ){
      this.$store.dispatch('createSocket')
    },

    //实时刷新点表
    handleFresh( ){
      this.$store.dispatch('sendProjectInfo')
      this.$store.commit('clearInit', { componentData: this.componentData } )
      this.$store.dispatch('callData')
    },

    //打开报警窗口
    handleAlarm( ){
      this.isShowAlarm = true 
    },

    handleResultAlarm(  ){
      this.isShowAlarm = false
    },

    handleResultAbout( ){
      this.isShowAbout = false ;
    },

    // async freshProjectSave( ){
    //   let res = await request.post( "/drwproject/freshrun" )
    //   if( res.code === "1" ){
    //      ElMessage.success( "刷新报警项目完成!" )
    //   }
    // },

  },
}
</script>

<style  lang="scss"  scoped>
.clsmenu{
  height: 10vh ;
}
</style>